package com.jiguang.shangcheng.servlet;

import com.jiguang.shangcheng.dao.AdminDao;
import com.jiguang.shangcheng.pojo.User;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/admin/admin_index")
public class adminIndex extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("UTF-8");


        //分页查询所有用户数据
        int page = 1;//当前页
        int count = 5;//每页显示数据

        //获取用户指定的页面
        String cp = req.getParameter("cp");
        if(cp != null){
            page = Integer.parseInt(cp);
        }
        //查询所有用户
        AdminDao adminDao = new AdminDao();
        List<User> userList = adminDao.selectAllUser(page,count);

        if(page != 1 && userList.size() == 0){
            PrintWriter out = resp.getWriter();
            out.println("<script>location.href='/admin/admin_index?cp="+(Integer.parseInt(cp)-1)+"';</script>");
            out.close();
            return;
        }

        //查询一共总数据以及总页数
        int sum[] = adminDao.selectPage(count);

        //返回数据
        req.setAttribute("page",page);//当前页
        req.setAttribute("sum",sum[0]);//总数据
        req.setAttribute("cpage",sum[1]);//总页数
        req.setAttribute("userList",userList);

        //返回首页
        req.getRequestDispatcher("admin_index.jsp").forward(req,resp);

    }
}
